package com.terracloud.server.dao.settings;

import com.terracloud.common.util.JacksonUtil;
import com.terracloud.server.common.data.AdminSettings;
import com.terracloud.server.common.data.id.TenantId;
import com.terracloud.server.common.data.security.model.encryption.EncryptionMode;
import com.terracloud.server.common.data.security.model.encryption.EncryptionSettings;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import static com.terracloud.server.common.data.CacheConstants.ENCRYPTION_SETTINGS_CACHE;

/**
 *
 * @author chenhainan
 * @since 2025/11/25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DefaultEncryptionSettingsService implements EncryptionSettingsService {

    private final AdminSettingsService adminSettingsService;

    @Override
    @Cacheable(cacheNames = ENCRYPTION_SETTINGS_CACHE, key = "'encryptionSettings'")
    public EncryptionSettings getEncryptionSettings() {
        AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "encryptionSettings");
        EncryptionSettings encryptionSettings;
        if (adminSettings != null) {
            try {
                encryptionSettings = JacksonUtil.convertValue(adminSettings.getJsonValue(), EncryptionSettings.class);
            } catch (Exception e) {
                throw new RuntimeException("Failed to load security settings!", e);
            }
        } else {
            encryptionSettings = new EncryptionSettings();
            encryptionSettings.setEncryptionMode(EncryptionMode.NONE);
        }
        return encryptionSettings;
    }

    @Override
    @CacheEvict(cacheNames = ENCRYPTION_SETTINGS_CACHE, key = "'encryptionSettings'")
    public EncryptionSettings saveEncryptionSettings(EncryptionSettings encryptionSettings) {
        AdminSettings adminSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "securitySettings");
        if (adminSettings == null) {
            adminSettings = new AdminSettings();
            adminSettings.setTenantId(TenantId.SYS_TENANT_ID);
            adminSettings.setKey("encryptionSettings");
        }
        adminSettings.setJsonValue(JacksonUtil.valueToTree(encryptionSettings));
        AdminSettings savedAdminSettings = adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, adminSettings);
        try {
            return JacksonUtil.convertValue(savedAdminSettings.getJsonValue(), EncryptionSettings.class);
        } catch (Exception e) {
            throw new RuntimeException("Failed to load encryption settings!", e);
        }
    }
}
